//
//  ZYTagView.m
//  AudientList
//
//  Created by zhangweiwei on 16/6/15.
//  Copyright © 2016年 Erica. All rights reserved.
//

#import "ZYTagView.h"
#import "ZYTagCell.h"
#import "ZYTagViewLayout.h"

@interface ZYTagView ()<UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) ZYTagViewLayout *layout;
@end

@implementation ZYTagView
#pragma mark -懒加载属性
- (ZYTagViewLayout *)layout
{
    if (!_layout) {
        _layout = [[ZYTagViewLayout alloc] init];
    }
    return _layout;
}

- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.layout];
        [_collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([ZYTagCell class]) bundle:nil] forCellWithReuseIdentifier:ZYTagCellReuseID];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.scrollEnabled = NO;
        
        
    }
    return _collectionView;
}

#pragma mark -初始化
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        [self setupUI];
        
    }
    return self;
}

- (void)setupUI
{
    [self addSubview:self.collectionView];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    self.collectionView.frame = self.bounds;
    
}

#pragma mark -UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.tagModels.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ZYTagCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ZYTagCellReuseID forIndexPath:indexPath];
    cell.tagModel = self.tagModels[indexPath.item];
    return cell;
}

#pragma mark -UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ZYTagModel *tagModel = self.tagModels[indexPath.item];
    
    CGFloat width = tagModel.textWidth + 20;
    
    if (tagModel.image) {
        width += tagModel.image.size.width + 5;
    }
    
    return CGSizeMake(width, ZYTagCellHeight);
    
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    !self.DidSelectedItemAtIndex ? : self.DidSelectedItemAtIndex(indexPath.item);
}

#pragma mark -公共方法
- (void)setTagModels:(NSArray *)tagModels
{
    _tagModels = tagModels;
    
    [self.collectionView reloadData];
}




@end
